import axios from "axios";
import store from "@/store";
import { showMessage } from "@/common/utils";
import { ERROR_MESSAGE, ERROR_TYPE, EVENT_KEYS } from "@/common/constants";
import EventBus from "@/config/eventBus";

const service = axios.create({
	baseURL: "https://apifoxmock.com/m1/5720149-0-default/yydf/api/v1",
	timeout: 5000
});

const customService = axios.create({
	baseURL: "http://localhost:8081",
	timeout: 5000
});

service.interceptors.request.use(
	(config) => {
		const token = store.state.user.token;
		if (token) {
			config.headers.Authorization = `Bearer ${token}`;
		}
		return config;
	},
	(error) => {
		showMessage(error.message || ERROR_MESSAGE.NETWORK_ERROR, false);
		return Promise.reject(error);
	}
);

service.interceptors.response.use(
	(response) => {
		const { msg, data, success } = response.data;
		const code = response.status;
		if (success) {
			return { code, msg, data };
		}
		switch (code) {
			case 401:
				EventBus.$emit(EVENT_KEYS.UNAUTHORIZED);
				break;
			case 500:
				EventBus.$emit(EVENT_KEYS.NETWORK_ERROR);
				break;
			default:
				showMessage(msg || ERROR_MESSAGE.NETWORK_ERROR, false);
				break;
		}
	},
	(error) => {
		showMessage(error.message || ERROR_MESSAGE.NETWORK_ERROR, false);
		return Promise.reject(error);
	}
);

customService.interceptors.request.use(
	(config) => {
		const userToken = store.state.user.token;
		const professorToken = store.state.professor.token;
		const token = userToken || professorToken;
		if (token) {
			config.headers.Authorization = `Bearer ${token}`;
		}
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

customService.interceptors.response.use(
	(response) => {
		const { msg, data, success } = response.data;
		const code = response.status;
		if (success) {
			return { code, msg, data, success };
		}
		return Promise.reject({
			code,
			msg: msg || ERROR_MESSAGE.NETWORK_ERROR,
			success,
			type: ERROR_TYPE.BUSINESS
		 });
	},
	(error) => {
		const code = error.response?.status;
		const msg = error.response?.data?.msg || ERROR_MESSAGE.NETWORK_ERROR;
		let type = ERROR_TYPE.BUSINESS;
		
		if (code === 401) {
			EventBus.$emit(EVENT_KEYS.UNAUTHORIZED);
			type = ERROR_TYPE.NETWORK;
		} else if (code === 500) {
			EventBus.$emit(EVENT_KEYS.NETWORK_ERROR);
			type = ERROR_TYPE.NETWORK;
		}
		return Promise.reject({ code, msg, success: false, type });
	}
);

export {
	service,
	customService
};
